package com.translator.engine.api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 谷歌翻译引擎实现
 * 使用谷歌翻译API进行文本翻译
 */
public class GoogleTranslationEngine extends AbstractAPITranslationEngine {
    
    private static final String API_URL = "https://translation.googleapis.com/language/translate/v2";
    
    /**
     * 构造函数
     */
    public GoogleTranslationEngine() {
        super("谷歌翻译");
    }
    
    @Override
    protected String doTranslate(String sourceText, String sourceLanguageCode, String targetLanguageCode) throws Exception {
        // 构建请求URL
        StringBuilder urlBuilder = new StringBuilder(API_URL);
        urlBuilder.append("?key=").append(apiKey);
        
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        
        // 构建请求体
        String requestBody = String.format("{\"q\":\"%s\",\"source\":\"%s\",\"target\":\"%s\",\"format\":\"text\"}", 
                escapeJson(sourceText), 
                sourceLanguageCode, 
                targetLanguageCode);
        
        // 发送请求
        try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)) {
            writer.write(requestBody);
        }
        
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        
        // 解析响应
        String responseBody = response.toString();
        String translatedText = parseResponse(responseBody);
        
        return translatedText;
    }
    
    /**
     * 解析API响应，提取翻译结果
     * 
     * @param responseBody API响应体
     * @return 翻译后的文本
     */
    private String parseResponse(String responseBody) {
        // 简单解析，实际应用中应使用JSON库
        int translatedTextStart = responseBody.indexOf("\"translatedText\":\"") + 18;
        int translatedTextEnd = responseBody.indexOf("\"", translatedTextStart);
        
        if (translatedTextStart >= 18 && translatedTextEnd > translatedTextStart) {
            return responseBody.substring(translatedTextStart, translatedTextEnd);
        }
        
        return "翻译失败，无法解析响应";
    }
    
    /**
     * 转义JSON字符串
     * 
     * @param input 输入字符串
     * @return 转义后的字符串
     */
    private String escapeJson(String input) {
        return input.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
    }
}